using IP2Region.Net.XDB;
using Microsoft.AspNetCore.Mvc;

namespace Yming.Tool.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class Ip2RegionController : ControllerBase
    {

        private readonly ILogger<Ip2RegionController> _logger;

        public Ip2RegionController(ILogger<Ip2RegionController> logger)
        {
            _logger = logger;
        }

        [HttpGet(Name = "SearchCacheContent")]
        public IP SearchCacheContent(string ip)
        {
            var contentSearcher = new Searcher(CachePolicy.Content);
            var region = contentSearcher.Search(ip);
            var regionArr = region?.Split("|");
            var result=new IP() 
            {
                Ip = ip,
                Country= regionArr?[0]=="0"?"": regionArr?[0],
                Province = regionArr?[2] == "0" ? "" : regionArr?[2],
                City = regionArr?[3] == "0" ? "" : regionArr?[3],
                Address = regionArr?[4] == "0" ? "" : regionArr?[0]+"-"+ regionArr?[2]+"-"+ regionArr?[3]+"-"+ regionArr?[4],
            };
            return result;
        }
    }
    public class IP
    {
        public string Ip { get; set; }
        public string? Country { get; set; } = string.Empty;

        public string? Province { get; set; }=string.Empty;

        public string? City { get; set; } = string.Empty;

        public string? Address { get; set; } = string.Empty;
    }
}